package com.hfb.io.netty.directbytebuffer;

import java.nio.ByteBuffer;

public class DirectMemoryTest {

    /**
     * 对内内存底层是一个数组
     */
    public static void heapAccess(){
        long s = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (int i = 0; i < 100_000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        System.out.printf("堆内存访问：%s ms\n", (System.currentTimeMillis()-s));
    }

    /**
     * 堆外内存是物理内存
     */
    public static void directAccess(){
        long s = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        for (int i = 0; i < 100_000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        System.out.printf("直接内存（堆外内存）访问：%s ms\n", (System.currentTimeMillis()-s));
    }

    public static void main(String[] args) {
        heapAccess();
        directAccess();
    }
}
